package net.easyjava.tools.http;

import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import net.easyjava.tools.BaseTools;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.io.PipedReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by wenxiaoning on 15/11/17.
 */
public class HttpTools extends BaseTools {
    private static final long serialVersionUID = 8497804668452773615L;
    private static int timeout = 10 * 1000;
    private static final String CHARSET_UTF_8 = "utf-8";


    /**
     * get data from url by GET
     *
     * @param url
     * @param heads
     * @return
     * @throws IOException
     */
    public static String get(String url, Map<String, String> heads) throws IOException {

        return get(url,heads,CHARSET_UTF_8);
    }

    public static String get(String url,Map<String,String> heads,String charset) throws IOException{
        HttpGet httpget = new HttpGet(url);

        //set heads
        if (heads != null) {
            for (String h : heads.keySet()) {
                httpget.setHeader(h, heads.get(h));
            }
        }
        HttpClient client = new DefaultHttpClient();
        HttpResponse response = client.execute(httpget);
        HttpEntity entity = response.getEntity();
        return  EntityUtils.toString(entity,charset).trim();
    }

    public static String get(String url) throws IOException {
        return get(url, null);
    }

    public static String post(String url) throws IOException {
        return post(url, null, null);
    }

    public static String post(String url, Map<String, String> params) throws IOException {
        return post(url, null, params);
    }

    /**
     * get data from url by POST with heads and params
     *
     * @param url
     * @param heads
     * @param params
     * @return
     * @throws IOException
     */
    public static String post(String url, Map<String, String> heads,
                              Map<String, String> params) throws IOException {
        BasicHttpParams httpParams = new BasicHttpParams();
        HttpConnectionParams.setSoTimeout(httpParams, timeout);

        HttpClient client = new DefaultHttpClient(httpParams);
        HttpPost post = new HttpPost(url);

        if (heads != null) {
            for (String h : heads.keySet()) {
                post.setHeader(h, heads.get(h));
            }
        }

        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        if (params != null) {
            for (String key : params.keySet()) {
                nvps.add(new BasicNameValuePair(key, params.get(key)));
            }
        }

        post.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
        HttpResponse response = client.execute(post);
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            return EntityUtils.toString(entity).trim();
        } else {
            return null;
        }
    }


    /**
     * get data from url by POST with json data
     *
     * @param url
     * @param json
     * @return
     * @throws IOException
     */
    public static String postJSON(String url, String json) throws IOException {
        if (json == null) {
            throw new NullPointerException(json + " can't be null");
        }
        try {
            JSONObject.parseObject(json);
        } catch (JSONException e) {
            throw new JSONException(json + " can't cast to com.alibaba.fastjson.JSONObject");
        }
        DefaultHttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost(url);
        String result = null;
        StringEntity s = new StringEntity(json);
        s.setContentEncoding("UTF-8");
        s.setContentType("application/json");//send json data need to set contentType
        post.setEntity(s);
        HttpResponse res = client.execute(post);
        if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            HttpEntity entity = res.getEntity();
            result = EntityUtils.toString(res.getEntity());
        }
        return result;
    }



    public static void main(String[] args) {
        try {
            String data = postJSON("http://data.zhengzai.tv/info/music/queryMusicPage", "hao");
            System.out.println("data = " + data);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}
